<template>
  <pre id="scripts">
<template v-for="item of dmls"><i v-if="item.indexOf('--') != -1">{{item}}</i><p v-else @click="copyDML(item)">{{item}}</p></template>
    </pre>
</template>

<script setup>
  import { useRoute } from 'vue-router';
  import { ref, inject, watch, onMounted } from 'vue';
  import { Toast } from 'vant';

  const $route = useRoute();

  const $http = inject('$http');
  const $copyText = inject('$copyText');

  const props = defineProps({
    table: String
  });

  const dmls = ref([]);

  watch(
    () => props.table,
    () => getTableDDL()
  );

  function getTableDDL() {
    let dbIndex = $route.params.dbIndex;
    let schema = $route.params.schema;
    let dbType = $route.query.dbtype;
    let tableName = props.table;

    if (dbIndex && schema && tableName) {
      $http.get(`/api/db/${dbIndex}/${schema}/${tableName}/dml`).then(res => (dmls.value = res.datas));
    }
  }

  function copyDML(text) {
    $copyText(text).then(() => {
      Toast.success('片段已复制！');
    });
  }

  function onCopyScript() {
    $copyText(document.getElementById('scripts').innerText).then(() => {
      Toast.success('脚本已复制！');
    });
  }

  onMounted(() => {
    getTableDDL();
  });
</script>

<style lang="less" scoped>
  #scripts {
    margin: 0;
    background: #fff;
    border-radius: 5px;
    padding: 5px 10px;
    overflow: auto;
    height: 100%;

    i {
      font-weight: bold;
      user-select: none;
    }

    p {
      cursor: pointer;
      user-select: all;
    }
  }
</style>
